﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BizzCommInterfaces;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace BizzCore
{
 
    /// 
    [Table("Rules")]
    public class Rule
    {
        //Ejemplo: Soy casado: Casado = true  -> Outbox
        [Key]
        public int Id { get; set; }
        
        [MaxLength(255)]
        public string ruleName {get; set;} // Soy casado:

        [MaxLength(255)]
        public string ruleField { get; set; } // Casado, edad

        [NotMapped]
        public Condition _condition { get; set; } // + == < > <= >= <>
        
        [MaxLength(255)]
        public string ruleExpectedValue { get; set; } // true, 30

        [NotMapped]
        public IOutbox _outbox { get; set; } // -> Outbox

        [MaxLength(5)]
        public string conditionString { get; set; }

        public virtual TrayEntity outboxEntity { get; set; }

        
        public Rule()
        {

        }
        
        public Rule(string name, string field, Condition condition, string expectedValue, IOutbox outbox)
        {
            this.ruleName = name;
            this.ruleField = field;
            this._condition = condition;
            this.ruleExpectedValue = expectedValue;
            this._outbox = outbox;
            this.conditionString = condition.ToString();
            this.outboxEntity = TraysHandler.getInstance().getTrayFromOutBox(outbox);

        }

        public IOutbox evaluateRule(BizzMessage msg)
        {
            IOutbox ret = null;

            var queryMatchingAttribute =
                   (from att in msg.Attributes
                   where att.Name == ruleField
                   select att).FirstOrDefault();

            if (queryMatchingAttribute != null)
            {
                bool satisfyCondition = false;
                MsgAttribute attribute = queryMatchingAttribute;
                satisfyCondition = _condition.evaluateCondition(attribute, ruleField, ruleExpectedValue);
                if (satisfyCondition)
                {
                    ret = this._outbox;
                }
            }

            return ret;
        }

        public override string ToString()
        {
            string ret = ruleName + ": ";
            ret += ruleField + " ";
            ret += _condition.ToString() + " ";
            ret += ruleExpectedValue + "->";
            ret += _outbox.getConcreteOutboxName();
            return ret;
        }
    }
}
